package web.sms.utils;

import cn.palerock.utils.StringUtils;
import web.sms.core.exception.AttributeCheckFailureException;
import web.sms.core.pojo.ErrorInfo;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * 时间： 2017/12/28
 *
 * @author Eoly
 */
public class ObjectUtils {
    /**
     * 检查实体及实体属性是否为空
     *
     * @param object     实体
     * @param errorInfo  当发生错误时的提示
     * @param properties 属性集合
     */
    public static void checkObjectProperties(Object object, ErrorInfo errorInfo, String... properties) {
        if (object == null) {
            throw new AttributeCheckFailureException(errorInfo, "null", new String[]{"实体对象为空"});
        }
        for (String attributeName : properties) {
            String methodName = "get" + StringUtils.captureName(attributeName);
            try {
                Object obj = object.getClass().getMethod(methodName).invoke(object);
                if (obj == null) {
                    throw new AttributeCheckFailureException(
                            errorInfo, attributeName,
                            new String[]{attributeName + "属性为空"});
                }
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            } catch (NoSuchMethodException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 令指定实体属性值设置为空
     *
     * @param object     实体
     * @param properties 实体属性集
     */
    public static void emptyUserProperties(Object object, ErrorInfo errorInfo, String... properties) {
        if (object == null) {
            throw new AttributeCheckFailureException(errorInfo, "null", new String[]{"实体对象为空"});
        }
        for (String attributeName : properties) {
            String methodName = "set" + StringUtils.captureName(attributeName);
            Method[] methods = object.getClass().getMethods();
            for (Method method : methods) {
                if (methodName.equals(method.getName())) {
                    try {
                        method.invoke(object, (Object) null);
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    } catch (InvocationTargetException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
}
